import { useUserStore } from "@/pinia/stores/user"
import { TUILogin } from "@tencentcloud/tui-core"
import { framework } from "../../../TUIKit/adapter-vue"
import { genTestUserSig, TUIChatKit } from "../../../TUIKit/index"
import TencentCloudChat from '@tencentcloud/chat';

import TUIChatEngine, {
  TUIConversationService,
  TUIFriendService,
  AddFriendParams
} from "@tencentcloud/chat-uikit-engine";


const userStore = useUserStore();

let chat = TencentCloudChat.create({
  SDKAppID: userStore.IM_SDKAppID
});
chat.setLogLevel(4);

export function init() {
  if (userStore.mobile) {
    // 必填信息
    // const config = {
    //   userID: userStore.PERFIX + userStore.mobile, // User ID
    //   SDKAppID: userStore.IM_SDKAppID,
    //   secretKey: userStore.IM_secretKey,
    // };
    // TUIChatKit 初始化
    TUIChatKit.init();
  }
}


export function login() {

  const { userSig } = genTestUserSig({
    SDKAppID: userStore.IM_SDKAppID,
    secretKey: userStore.IM_secretKey,
    userID: userStore.PERFIX + userStore.mobile
  })
  userStore.setUserSig(userSig);

  if (userStore.mobile) {
    // TUIChatKit 初始化
    TUIChatKit.init();

    // TUICore login
    TUILogin.login({
      SDKAppID: userStore.IM_SDKAppID,
      userID: userStore.PERFIX + userStore.mobile,
      // UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文。
      // 该方法仅适合本地跑通 Demo 和功能调试，详情请参见 https://cloud.tencent.com/document/product/269/32688
      userSig,
      // 如果您需要发送图片、语音、视频、文件等富媒体消息，请设置为 true
      useUploadPlugin: true,
      // 本地审核可识别、处理不安全、不适宜的内容，为您的产品体验和业务安全保驾护航
      // 此功能为增值服务，请参考：https://cloud.tencent.com/document/product/269/79139
      // 如果您已购买内容审核服务，开启此功能请设置为 true
      useProfanityFilterPlugin: false,
      framework // 当前开发使用框架 vue2 / vue3
    }).then(() => {


    });

  }
}

export function logout() {
  let promise = chat.logout();
  promise.then(function (imResponse) {
    console.log("imResponse====", imResponse); // 登出成功
  }).catch(function (imError) {
    console.warn('logout error:', imError);
  });
}


export function destroy() {
  let promise = chat.destroy();
  promise.then(function (imResponse) {
    console.log("destroy1111111====", imResponse); // 销毁成功
  }).catch(function (imError) {
    console.warn('destroy error:', imError);
  });
}


export async function createC2CConversation(to_mobile: string | undefined) {
  // 即时聊天权限与业务控制

  let mobile = userStore.mobile;

  console.log('发送方的手机' + mobile, '接收者手机号' + to_mobile)

  if (mobile === to_mobile) {
    ElMessage.error("不能与自己聊天")
    return false
  }

  if ((to_mobile == 'undefined') || (to_mobile == undefined)) {
    to_mobile = 'customer001';
  }

  let isBothFriend = await isFriend({
    userID: userStore.PERFIX + to_mobile
  });

  const conversationID = `C2C${userStore.PERFIX + to_mobile}`;

  TUIConversationService.getConversationProfile(conversationID)
    .then((res) => {
      if (!isBothFriend) {
        let obj = {
          to: userStore.PERFIX + to_mobile,
          source: "AddSource_Type_Web",
        }
        addFriend(obj);
      }
      TUIConversationService.switchConversation(
        res.data.conversation.conversationID
      );
      userStore.setOpenIM(true);
    })
    .catch((err) => {
      console.warn("打开会话失败", err.code, err.msg);
      createC2CConversation('iaYt02jzhHmoCCCqGpaxf5G0VzuMPwLU')
    });
}


const isFriend = (info: { userID: any; groupID?: any; addTime?: any; }) => {
  return new Promise((resolve, reject) => {
    if (info?.groupID || !info?.userID) {
      resolve(false);
      return;
    }
    if (info?.addTime) {
      resolve(true);
      return;
    }
    TUIFriendService.checkFriend({
      userIDList: [info?.userID],
      type: TUIChatEngine.TYPES.SNS_CHECK_TYPE_BOTH,
    })
      .then((res) => {
        switch (res?.data?.successUserIDList[0]?.relation) {
          // 无好友关系：A 的好友表中没有 B，B 的好友表中也没有 A
          case TUIChatEngine.TYPES.SNS_TYPE_NO_RELATION:
            resolve(false);
            break;
          // 单项好友：A 的好友表中有 B，但 B 的好友表中没有 A
          case TUIChatEngine.TYPES.SNS_TYPE_A_WITH_B:
            resolve(false);
            break;
          // 单项好友：A 的好友表中没有 B，但 B 的好友表中有 A
          case TUIChatEngine.TYPES.SNS_TYPE_B_WITH_A:
            resolve(false);
            break;
          // 双向好友关系
          case TUIChatEngine.TYPES.SNS_TYPE_BOTH_WAY:
            resolve(true);
            break;
          default:
            resolve(false);
            break;
        }
      })
      .catch((error) => {
        console.warn("checkFriend error", error);
        reject(error);
      });
  });
};

const addFriend = (params: AddFriendParams) => {
  TUIFriendService.addFriend(params)
    .then((res) => {

    })
    .catch((error) => {
      console.warn("delete friend failed:", error);
    });
};
